import { containsPoint } from "../js/utils/index.js"

class TextLine {
    constructor(x = 0, y = 0) {
        this.text = ''
        this.caret = 0
        this.x = x
        this.y = y
        this.background = 'rgba(200, 0, 0, 0.3)'
        this.color = '#ffffff'
    }

    getBottom(context) {
        return this.y + this.getHeight(context)
    }

    insert(text) {
        this.text = this.text.substr(0, this.caret) + text + this.text.substr(this.caret)
        this.caret += text.length
    }

    getWidth(context) {
        return Math.round(context.measureText(this.text).width)
    }

    getHeight(context) {
        let w = context.measureText('w').width
        let h = w + w / 6
        return Math.round(h)
    }
    getLetterWidth(context) {
        let w = context.measureText('w').width
        return w
    }
    setCaret(index) {
        if (index > 0 && index < this.text.length) {
            this.caret = index;
        }
    }

    forwardCursor() {
        if (this.caret < this.text.length) {
            this.caret++;
        }
    }

    backwardCursor() {
        if (this.caret > 0) {
            this.caret--;
        }
    }
    homeCursor() {
        this.caret = 0
    }
    endCursor() {
        this.caret = this.text.length
    }

    removeCharBeforeCaret() {
        if (this.caret === 0) {
            return
        }
        this.text = this.text.substring(0, this.caret - 1) + this.text.substring(this.caret);

        this.caret--
    }

    update() {

    }

    draw(context, ox, oy) {
        context.save();
        context.textAlign = 'start';
        context.textBaseLine = 'bottom';
        this.drawBackground(context, ox, oy);

        let bottom = this.getBottom(context);
        context.fillStyle = this.color;
        context.fillText(this.text, this.x + ox, bottom + oy);
        context.restore();
    }

    getCursorPosition(ctx) {
        let subTxt = this.text.substring(0, this.caret);
        let x = this.x + ctx.measureText(subTxt).width;
        return {
            x: x,
            y: this.y
        }
    }

    getBoundingRect(context) {
        let x = this.x;
        let y = this.y;
        let w = this.getWidth(context);
        let h = this.getHeight(context);

        return {
            x: x,
            y: y,
            width: w,
            height: h,
        }
    }

    drawBackground(context, ox, oy) {
        const { x, y, width, height } = this.getBoundingRect(context);
        context.save();
        context.fillStyle = this.backgroundColor;
        context.beginPath();
        context.fillRect(x + ox, y + oy, width, height);
        context.restore();
    }

    containsPoint(context, x, y) {
        let rect = this.getBoundingRect(context)
        return containsPoint(rect, x, y)
    }
}


export { TextLine }